<?php
/**
 * Api 响应
 * Author: Zeon
 * Date: 2017-12-20
 * Created by Panxsoft.
 */
namespace App\Services\Utils;

use Illuminate\Http\Response;

trait ApiResponser
{
    /**
     * @var int - api 正常返回码
     */
    protected static $API_OK = 0;

    /**
     *
     * @param mixed $compact_data
     * @param int $status
     * @param array $headers
     * @return array|\Illuminate\Http\Response
     */
    protected function response($compact_data = null, $status = Response::HTTP_OK, array $headers = [])
    {
        $content = $this->normalizeResponseData($compact_data);

        return response($content, $status, $headers);
    }

    /**
     *
     * @param mixed $compact_data
     * @param array $headers
     * @return array|\Illuminate\Http\Response
     */
    protected function responseCreated($compact_data = null, array $headers = [])
    {
        $content = $this->normalizeResponseData($compact_data);

        return response($content, Response::HTTP_CREATED, $headers);
    }

    /**
     *
     * @param mixed $compact_data
     * @param array $headers
     * @return array|\Illuminate\Http\Response
     */
    protected function responseAccepted($compact_data = null, array $headers = [])
    {
        $content = $this->normalizeResponseData($compact_data);

        return response($content, Response::HTTP_ACCEPTED, $headers);
    }

    /**
     * 可以传入 JSON 参数
     *
     * @param mixed $compact_data
     * @param int $json_option
     * @param int $status
     * @param array $headers
     * @return array|\Illuminate\Http\Response
     */
    protected function responseJson($compact_data, $json_option = 0, $status = Response::HTTP_OK, array $headers = [])
    {
        $content = $this->normalizeResponseData($compact_data);

        return response()->json($content, $status, $headers, $json_option);
    }

    /**
     * 处理返回数据变成数组，trait中的private不能在use trait 的类中调用，只能通过 trait 中的方法如 protect public 等方法）
     * 如果需要同名调用需要在 trait 中 __call
     *
     * @param mixed $compact_data
     * @return array
     */
    private function normalizeResponseData($compact_data)
    {
        $code = ['code' => self::$API_OK];

        /** @var array $compact_data */
        $compact_data = is_array($compact_data)
            ? $compact_data
            : ['data' => $compact_data];

        $content = array_merge($code, $compact_data);

        return $content;
    }

}